package com.hohai.river.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import com.hohai.river.entity.River;
import com.hohai.river.mapper.RiverMapper;
import com.hohai.river.service.RiverService;
import com.hohai.river.utils.JsonUtils;
import com.pig4cloud.pig.common.security.util.SecurityUtils;
import io.swagger.v3.core.util.Json;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class RiverServiceImpl extends ServiceImpl<RiverMapper, River> implements RiverService {

	@Override
	public List<River> selectByCountyIds(List<Long> countyIds) {
		return this.baseMapper.selectByCountyIds(countyIds);
	}

	@Override
	public boolean updateSystemScore(Long riverId, Double score) {
		Long userId = SecurityUtils.getUser().getId();
		River river = this.baseMapper.selectById(riverId);
		JSONObject jsonObject;
		if (StringUtils.isEmpty(river.getExpertList())) {
			jsonObject = new JSONObject();
		}
		else {
			jsonObject = JSON.parseObject(river.getExpertList());
		}
		jsonObject.put(userId.toString(), score);
		score = jsonObject.keySet().stream().mapToDouble(jsonObject::getDouble).average().orElse(0);
		river.setSystemScore(score);
		river.setExpertList(jsonObject.toJSONString());
		return SqlHelper.retBool(this.baseMapper.updateById(river));
	}

	@Override
	public List<River> getAllIndexScores(Long riverId) {
		return this.baseMapper.getAllIndexScores(riverId);
	}

}
